import { createStoreBindings } from 'mobx-miniprogram-bindings'
import { store } from '../../store/store'
const util = require('../../utils/util')

Page({
  data: {
    cellphone: '',
    msg: '',
    loading: false
  },
  onLoad(options) {
    this.storeBindings = createStoreBindings(this, {
      store,
      actions: ['setToken'],
    })
    if (options.cellphone) {
      this.setData({
        cellphone: options.cellphone
      })
    }
  },
  onUnload() {
    this.storeBindings.destroyStoreBindings()
  },
  /**
   * 表单提交事件
   */
  formSubmit(e) {
    const params = e.detail.value || {}
    if (!params.cellphone) {
      return this.setData({
        msg: '手机号不能为空'
      })
    } else {
      if (!/^1[23456789]\d{9}$/.test(params.cellphone)) {
        return this.setData({
          msg: '手机号码有误'
        })
      }
    }
    if (!params.password) {
      return this.setData({
        msg: '密码不能为空'
      })
    } else {
      if (params.password.length < 6 || params.password.length > 20) {
        return this.setData({
          msg: '密码长度为6-20位'
        })
      }
    }
    this.setData({
      loading: true
    })
    wx.showLoading({ title: '加载中…', mask: true })
    util.throttle(this.login(params))
  },
  /**
   * 登录事件
   */
  login(params) {
    wx.cloud.callFunction({
      name: 'login',
      data: {
        ...params
      },
      complete: res => {
        const r = res.result || {}
        if (r.code == 200) {
          wx.showToast({
            title: '登录成功',
            icon: 'success',
            duration: 2000,
            mask: true,
            complete: () => {
              this.setData({
                loading: false
              })
              wx.hideLoading()
              this.setToken(JSON.stringify(params))
              setTimeout(() => {
                wx.switchTab({
                  url: '../wallet/wallet'
                })
              }, 500);
            }
          })
        } else {
          this.setData({
            loading: false
          })
          wx.hideLoading()
          this.setData({
            msg: res.msg
          })
        }
      }
    })
  }
})